<!DOCTYPE html>
<html>
<body>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>

<iframe id="testIframe" sandbox="allow-scripts allow-same-origin" style="display:none">
</iframe>

<script>
var test = async_test("Test subframes receive window orientationchange events (includes window.onorientationchange and an event listener for orientationchange)");

if (window.internals && internals.runtimeFlags.orientationEventEnabled) {
  var orientations = [
    'portrait-primary',
    'portrait-secondary',
    'landscape-primary',
    'landscape-secondary'
  ];

  var orientationAngles = [
    0,
    180,
    90,
    -90
  ];

  var currentIndex = 0;
  var eventsReceived = 0;
  var numOrientationChanges = 0;

  function getNextIndex() {
    return (currentIndex + 1) % orientations.length;
  }

  function changeOrientation() {
    testRunner.setMockScreenOrientation(orientations[getNextIndex()]);
    currentIndex = getNextIndex();
    ++numOrientationChanges;
  }

  window.onmessage = test.step_func(function (ev) {
    assert_equals(ev.data, orientationAngles[currentIndex], "subframe received orientationchange event (window.screen.orientation.type=" + window.screen.orientation.type + ")");
    ++eventsReceived;

    // Once *both* of the event handlers/listeners have seen this event,
    // change the orientation or end the test.
    if ((eventsReceived % 2) == 0) {
      assert_equals(eventsReceived, numOrientationChanges*2);

      if (numOrientationChanges < 4) {
        changeOrientation();
      } else if (numOrientationChanges == 4) {
        test.done();
      }
    }
  });

  var testIframe = document.getElementById("testIframe");
  testIframe.src = "resources/iframe-listen-window-orientationchange.html";
  testIframe.onload = changeOrientation;
} else {
  console.error("This test requires window.internals and the orientationchange event to be enabled.");
  test.done();
}
</script>
</body>
</html>
